const Koa = require("koa");
const KoaRouter = require("koa-router");
const path = require('path');
const fs = require('fs');
const schedule = require('node-schedule')
const main = require('./src/main.js');
const getlist = require("./src/getlist.js");

schedule.scheduleJob('0 0 10 * * 1-5', main)

const router = new KoaRouter();

router.get("/", async (ctx) => {
  ctx.set('Content-Type', 'text/html');
  const html = fs.readFileSync(path.join(__dirname, 'src/view/index.html')).toString();
  const list = await getlist();
  if (list && list.length) {
    ctx.body = html.replace('{{script}}', `<script>const list = ${JSON.stringify(list, null, 2)}</script>`);
  } else {
    ctx.body = "<h1>accessToken 过期</h1>"
  }
});

router.all(/\/.*/, async (ctx) => {
  ctx.redirect("/")
});

const app = new Koa();

app.use(router.routes()).use(router.allowedMethods());

app.listen(4101);